package com.lzw.service.impl.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lzw.mapper.admin.BuildingManagementMapper;
import com.lzw.mapper.admin.DormitoryManagementMapper;
import com.lzw.mapper.admin.StudentManagementMapper;
import com.lzw.pojo.Building;
import com.lzw.service.admin.BuildingManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BuildingManagementServiceImpl implements BuildingManagementService {

    @Autowired
    private BuildingManagementMapper buildingManagementMapper;

    @Autowired
    private StudentManagementMapper studentManagementMapper;

    @Autowired
    private DormitoryManagementMapper dormitoryManagementMapper;

    @Override
    public List<Building> listBuildings(Integer pageNum, Integer pageSize, String name, String address) {
        PageHelper.startPage(pageNum,pageSize);
        List<Building> list = buildingManagementMapper.listBuildings(name,address);
        Page<Building> buildings = (Page<Building>) list;
        return  buildings;
    }

    @Override
    public boolean isNameExist(String name) {
        return buildingManagementMapper.countByName(name) > 0;
    }

    @Override
    public void addBuilding(Building building) {
        if (isNameExist(building.getName())) {
            throw new IllegalArgumentException("楼宇名称已存在，无法添加！");
        }
        buildingManagementMapper.addBuilding(building);
    }

    @Override
    public void deleteBuilding(List<Integer> ids) {
        buildingManagementMapper.deleteBuilding(ids);
        studentManagementMapper.deleteByBuildingById(ids);
        dormitoryManagementMapper.deleteDormitoryByBuildingId(ids);
    }

    @Override
    public Building getBuildingById(int id) {
        return buildingManagementMapper.getBuildingById(id);
    }

    @Override
    public void updateBuilding(Building building) {
        // 获取当前楼宇的信息
        Building existingBuilding = buildingManagementMapper.getBuildingById(building.getBuildingId());

        // 如果名称被修改，并且新名称已存在，则抛出异常
        if (!existingBuilding.getName().equals(building.getName())){
            if (isNameExist(building.getName())) {
                throw new IllegalArgumentException("楼宇名称已存在，无法更新！");
            }
        }

        // 更新楼宇信息
        buildingManagementMapper.updateBuilding(building);
    }
}
